/**
 * @product: SOD
 * @copyright: FSAI-南征北战信息科技
 * @filename: com.sod.controller.PageErrorController.java
 *
 * @link: Http://www.fastsai.com
 * @jdkv: Jdk 1.8
 */
package com.fsai.cms.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @project: sod-web-admin
 *
 * @author: JaffeHe
 * @email: JaffeHe@foxmail.com
 * @date: 2020-06-08 12:22
 *
 * @ChangeLog<br/>
 * 				Developer Date Comment <br/>
 */
@Controller
public class PageErrorController implements ErrorController {
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	public String getErrorPath() {
		return "/error";
	}

	@RequestMapping("/error")
	public ModelAndView handError(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		boolean isAdmin = isAdmin(request);
		if (StringUtils.isNotBlank(getReferer(request))) {
			isAdmin = getReferer(request).contains("admin");
		}
		mv.addObject("backIndex", isAdmin ? "/admin/index" : "/");

		log.error("访问" + request.getRequestURI() + "发生了错误，是否Admin:" + isAdmin + "---错误代码--" + statusCode
				+ "==getReferer:" + getReferer(request) + ":from:" + getFrom(request));
		if (statusCode == 401) {
			mv.setViewName("public/pg404");
			return mv;
		} else if (statusCode == 404) {
			mv.setViewName("public/pg404");
			return mv;
		} else if (statusCode == 403) {
			mv.setViewName("public/pg404");
			return mv;
		} else {
			mv.setViewName("public/pg500");
			return mv;
		}
	}

	/**
	 * 是否管理员访问
	 */
	private boolean isAdmin(HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		return requestURI.contains("admin");
	}

	public static String getReferer(HttpServletRequest request) {
		String res = "-none-";
		res = request.getHeader("Referer");
		if (StringUtils.isBlank(res)) {
			res = request.getHeader("referer");
		}

		return res;
	}

	public static String getFrom(HttpServletRequest request) {
		String res = "-none-";
		res = request.getHeader("From");
		if (StringUtils.isBlank(res)) {
			res = request.getHeader("from");
		}

		return res;
	}
}
